package chenxi.concurrent;

import java.util.Random;
import java.util.concurrent.*;

/**
 * @author bowen
 */
public class FutureTest {

    static final long waitTime = 8 * 1000;
    static final long awaitTime =  1000;
    // 创建线程池
    final static ExecutorService service = Executors.newCachedThreadPool();

    public static void main(String[] args)  {
        Long t1 = System.currentTimeMillis();

        // 任务1
        Future<Boolean> booleanTask = service.submit(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                Thread.sleep(waitTime);
                System.out.println("true");
                return true;
            }
        });

//        while (true) {
//            if (booleanTask.isDone() && !booleanTask.isCancelled()) {
//                //模拟耗时
//                Thread.sleep(500);
//                Boolean result = booleanTask.get();
//                System.err.println("BooleanTask: " + result);
//                break;
//            }
//        }

        // 任务2
        Future<String> stringTask = service.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                System.out.println("hello world");
                return "Hello World";
            }
        });

//        while (true) {
//            if (stringTask.isDone() && !stringTask.isCancelled()) {
//                String result = stringTask.get();
//                System.err.println("StringTask: " + result);
//                break;
//            }
//        }



        // 任务3
        Future<Integer> integerTask = service.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                Thread.sleep(waitTime);
                return new Random().nextInt(100);
            }
        });

//        while (true) {
//            if (integerTask.isDone() && !integerTask.isCancelled()) {
//                Integer result = integerTask.get();
//                System.err.println("IntegerTask: " + result);
//                break;
//            }
//        }

        service.shutdown();

        try {
            if (!service.awaitTermination(awaitTime, TimeUnit.MILLISECONDS)) {
                service.shutdownNow();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("end");

        // 执行时间
        System.err.println("time: " + (System.currentTimeMillis() - t1));
    }

}
